//
//  GWEmotionTextView.m
//  新浪微博
//
//  Created by qianfeng on 16/2/21.
//  Copyright (c) 2016年 高炜. All rights reserved.
//

#import "GWEmotionTextView.h"
#import "GWEmotion.h"
#import "GWEmotionAttachment.h"
@implementation GWEmotionTextView


-(void)addEmotion:(GWEmotion *)emotion
{
    NSMutableAttributedString *attrString =[[NSMutableAttributedString alloc]initWithAttributedString:self.attributedText];
    NSInteger loc =self.selectedRange.location;
    if (emotion.emoji) {
        NSAttributedString *str =[[NSAttributedString alloc]initWithString:emotion.emoji];
         [attrString insertAttributedString:str atIndex:loc];
    }else
    {
        GWEmotionAttachment *atch =[[GWEmotionAttachment alloc]init];
        atch.emotion =emotion;
        CGFloat imageW =self.font.lineHeight;
        atch.bounds =CGRectMake(0, -3, imageW, imageW);
        NSAttributedString *atStr =[NSAttributedString attributedStringWithAttachment:atch];
        
        [attrString insertAttributedString:atStr atIndex:loc];
    }
    [attrString addAttributes:@{NSFontAttributeName:self.font} range:NSMakeRange(0, attrString.length)];
    self.attributedText =attrString;
    self.selectedRange =NSMakeRange(loc+1, 0);
}

-(NSString *)realText
{
    NSMutableString *string =[NSMutableString string];
    
    [self.attributedText enumerateAttributesInRange:NSMakeRange(0, self.attributedText.length) options:0 usingBlock:^(NSDictionary *attrs, NSRange range, BOOL *stop) {
        GWEmotionAttachment *attach =attrs[@"NSAttachment"];
        if (attach) {
            [string appendString:attach.emotion.chs];
        }
        else
        {
            [string appendString:[self.attributedText attributedSubstringFromRange:range].string];
        }
    }];
    return string;
}
@end
